package configs

import (
	"encoding/json"
	"github.com/spf13/viper"
	"go-base/src/logs"
)

var Conf = &Config{}

func Init(filename string) {
	viper.SetConfigName(filename)
	viper.SetConfigType("toml")
	viper.SetConfigFile("./src/configs/config.toml")
	err := viper.ReadInConfig()
	if err != nil {
		logs.Error.Printf("Fatal error config file: %s \n", err)
	}
	//系统配置
	Conf.Version = viper.GetString("system.version")
	Conf.ReleaseMode = viper.GetString("system.releaseMode")
	//http服务配置
	Conf.BindIp = viper.GetString("http.bind_ip")
	Conf.BindPort = viper.GetUint32("http.bind_port")
	Conf.UseHttps = viper.GetBool("http.use_https")
	Conf.Cert = viper.GetString("http.cert")
	Conf.Key = viper.GetString("http.key")
	//sql数据库配置
	Conf.DbType = viper.GetString("db.type")
	Conf.DbHost = viper.GetString("db.host")
	Conf.DbPort = viper.GetUint32("db.port")
	Conf.DbUsername = viper.GetString("db.username")
	Conf.DbPassword = viper.GetString("db.password")
	Conf.DbName = viper.GetString("db.dbname")
	Conf.DbCharset = viper.GetString("db.charset")
	Conf.MaxIdleConns = viper.GetUint32("db.maxIdleConns")
	Conf.MaxOpenConns = viper.GetUint32("db.maxOpenConns")
	Conf.TimeZone = viper.GetString("db.timeZone")
	//mongodb数据库配置
	Conf.MongoHost = viper.GetString("mongo.mongo_host")
	Conf.MongoName = viper.GetString("mongo.mongo_name")
	Conf.MongoUser = viper.GetString("mongo.mongo_user")
	Conf.MongoPass = viper.GetString("mongo.mongo_pass")
	//redis配置
	Conf.RedisHost = viper.GetString("redis.redis_host")
	Conf.RedisPass = viper.GetString("redis.redis_pass")
	Conf.RedisPrefix = viper.GetString("redis.redis_prefix")
	//kafka配置
	Conf.KafkaUrl = viper.GetString("kafka.kafka_url")
	Conf.KafkaGroup = viper.GetString("kafka.kafka_group")
	Conf.KafkaTopic = viper.GetString("kafka.kafka_topic")
	//日志配置
	Conf.LogUrl = viper.GetString("logs.log_url")
	Conf.LogAge = viper.GetInt("logs.log_age")
	Conf.LogSize = viper.GetInt("logs.log_size")
	Conf.MaxBackups = viper.GetInt("logs.max_backups")
	Conf.Compress = viper.GetBool("logs.compress")
	//swagger配置
	Conf.JsonUrl = viper.GetString("swagger.json_url")
	Conf.IndexUrl = viper.GetString("swagger.index_url")

	bytes, err := json.MarshalIndent(Conf, "", "\t")
	if err != nil {
		logs.Error.Printf("初始化配置转json失败，err:%s", err)
	}
	logs.Info.Printf("配置: %+v", string(bytes))
}
